<template>
  <el-dialog
    :title="title"
    :visible.sync="visible"
    width="1200px"
    custom-class="scrollable-dialog"
    :close-on-click-modal="false"
  >
   <el-form
      size="small"
      :model="storeForm"
      ref="storeForm"
      label-position="top">
   <el-row :gutter="20">
    <el-col :span="12">
        <el-form-item
        label="入库类别（支持多选）"
        prop="supplierStoreIds"
        :rules="[
          { required: true, message: '请选择入库类别', trigger: 'change' }
        ]"
      >
        <el-cascader
          style="width:100%"
          placeholder="请选择入库类别，支持搜索"
          filterable
          v-model="storeForm.supplierStoreIds"
          :options="treeData"
          :props="{multiple: true,emitPath: false}"
          clearable
        ></el-cascader>
      </el-form-item>
    </el-col>
    <el-col :span="12">
        <el-form-item label="是否上传资质证书">
        <el-radio-group v-model="storeForm.isType" @change="typeChange">
          <el-radio :label="1">是</el-radio>
          <el-radio :label="2">否</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-col>
    </el-row>

  <div class="cumot-filex">
       <el-card class="box-card">
        <div slot="header" class="clearfix">
          <template v-if="storeForm.isType == 1">
             <span>资质证书</span>
          </template>
          <template v-else>
            资质证书
          </template>
        </div>
        <div class="mut-box">
           <el-upload
            accept="image/*,application/pdf"
            list-type="picture"
            :on-preview="handlePreview"
            :file-list="qualificationCertificateFileList"
            :on-remove="function(file, fileList) {return handleRemove(file, fileList, 'qualificationCertificateFileList')}"
            :before-upload="beforeAvatarUpload"
            action="#"
            :http-request="function(file, fileList) { return handleChange( file, fileList, 'qualificationCertificateFileList')}">
            <el-button type="primary" :disabled="storeForm.isType == 2" size="mini">选择上传</el-button>
            <div slot="tip" class="cumost-upload-tip">
              支持图片和pdf
            </div>
          </el-upload>
          <template v-if="qualificationCertificateFileList.length">
            <div class="blocks-file" v-for="(item,index) in qualificationCertificateFileList" :key="index">
              <label class="demonstration">{{ item.name }}</label>
              <div class="lbs">
                <el-date-picker
                  v-model="item.time"
                  type="daterange"
                  style="width: 100%;"
                  value-format="yyyy-MM-dd"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期">
                </el-date-picker>
              </div>
            </div>
          </template>
        </div>
      </el-card>
     <el-card class="box-card">
        <div slot="header" class="clearfix">
          <template v-if="storeForm.isType == 2">
             <span>不上传资质证书理由</span>
          </template>
          <template v-else>
            不上传资质证书理由
          </template>
        </div>
        <div class="mut-box">
           <el-input
            type="textarea"
            :rows="5"
            :disabled="storeForm.isType == 1"
            v-model="storeForm.qualificationCertificateFileReason"
            placeholder="请输入不上传资质理由"
          ></el-input>
        </div>
      </el-card>
       <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>业绩资料</span>
        </div>
         <div class="mut-box">
          <p style="margin-top: 0;line-height: 20px;">
            提供符合公告要求的业绩（金额、个数、类别、时间），并提供对应的转款凭证或发票；若是新项目暂未产生费用，请提供书面说明并盖章
          </p>
           <el-upload
            accept="image/*,application/pdf"
            list-type="picture"
            :on-preview="handlePreview"
            :file-list="performanceFileList"
            :on-remove="function(file, fileList) {return handleRemove(file, fileList, 'performanceFileList')}"
            :before-upload="beforeAvatarUpload"
            action="#"
            :http-request="function(file, fileList) {return handleChange(file, fileList, 'performanceFileList')}">
            <el-button type="primary" size="mini">选择上传</el-button>
            <div slot="tip" class="cumost-upload-tip">
              支持图片和pdf
            </div>
          </el-upload>
         </div>
        </el-card>
         <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>财务报告（报表）</span>
        </div>
         <div class="mut-box">
            <el-upload
          accept="image/*,application/pdf"
          list-type="picture"
          :on-preview="handlePreview"
          :file-list="financialReportFileList"
          :on-remove="function(file, fileList) { return handleRemove(file, fileList, 'financialReportFileList') }"
          :before-upload="beforeAvatarUpload"
          action="#"
          :http-request="function(file, fileList) { return handleChange(file, fileList, 'financialReportFileList') }">
          <el-button type="primary" size="mini">选择上传</el-button>
          <div slot="tip" class="cumost-upload-tip">
            支持图片和pdf
          </div>
        </el-upload>
         </div>
        </el-card>

        <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>缴纳税收证明或完税证明</span>
          <el-button type="text" style="float: right; padding: 0" @click="getKeyResult('egimg1','缴纳税收证明或完税证明示例图')" size="mini">【查看示例图】</el-button>
        </div>
         <div class="mut-box">
           <el-upload
          accept="image/*,application/pdf"
          list-type="picture"
          :on-preview="handlePreview"
          :file-list="taxFileList"
          :on-remove="function(file, fileList) { return handleRemove(file, fileList, 'taxFileList') }"
          :before-upload="beforeAvatarUpload"
          action="#"
          :http-request="function(file, fileList) {return handleChange(file, fileList, 'taxFileList')}">
          <el-button type="primary" size="mini">选择上传</el-button>
          <div slot="tip" class="cumost-upload-tip">
            支持图片和pdf
          </div>
        </el-upload>
         </div>
         </el-card>
         <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>缴纳社保证明</span>
          <el-button type="text" style="float: right; padding: 0" @click="getKeyResult('egimg2','缴纳社保证明示例图')" size="mini">【查看示例图】</el-button>
        </div>
         <div class="mut-box">
           <el-upload
          accept="image/*,application/pdf"
          list-type="picture"
          :on-preview="handlePreview"
          :file-list="socialSecurityFileList"
          :on-remove="function(file, fileList) { return handleRemove(file, fileList, 'socialSecurityFileList')}"
          :before-upload="beforeAvatarUpload"
          action="#"
          :http-request="function(file, fileList) { return handleChange(file, fileList, 'socialSecurityFileList')}">
          <el-button type="primary" size="mini">选择上传</el-button>
          <div slot="tip" class="cumost-upload-tip">
            支持图片和pdf
          </div>
        </el-upload>
         </div>
         </el-card>
          <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>良好的商业信誉</span>
           <el-button type="text" style="float: right; padding: 0" @click="getKeyResult('egimg3','商业信誉示例图')" size="mini">【查看示例图】</el-button>
        </div>
         <div class="mut-box">
          <p style="margin-top: 0;line-height: 20px;">
            ①提供“信用中国 <a style="color: rgb(64, 158, 255);" href="https://www.creditchina.gov.cn/" target="_blank">https://www.creditchina.gov.cn/</a> 网站相关截图证明；
          </p>
          <p style="margin-top: 0;line-height: 20px;">
            ②提供“国家企业信用公示系统 <a href="https://www.gsxt.gov.cn/" style="color: rgb(64, 158, 255);" target="_blank">https://www.gsxt.gov.cn/</a> 网站相关截图证明;
          </p>
            <el-upload
          accept="image/*,application/pdf"
          list-type="picture"
          :on-preview="handlePreview"
          :file-list="businessCreditFileList"
          :on-remove="function(file, fileList) {return handleRemove(file, fileList, 'businessCreditFileList')}"
          :before-upload="beforeAvatarUpload"
          action="#"
          :http-request="function(file, fileList) {return handleChange(file, fileList, 'businessCreditFileList')}">
          <el-button type="primary" size="mini">选择上传</el-button>
          <div slot="tip" class="cumost-upload-tip">
            支持图片和pdf
          </div>
        </el-upload>
         </div>
         </el-card>
         <el-card class="box-card">
        <div slot="header" class="clearfix">
         其他
        </div>
         <div class="mut-box">
          <div style="margin-bottom: 10px;">
            <el-input
              type="textarea"
              :rows="5"
              maxlength="300"
              show-word-limit
              v-model="storeForm.otherRemarks"
              placeholder="备注信息，限制300个文字"
            ></el-input>
          </div>
          <el-upload
          accept="image/*,application/pdf"
          list-type="picture"
          :on-preview="handlePreview"
          :file-list="otherFileList"
          :on-remove="function(file, fileList) {return handleRemove(file, fileList, 'otherFileList')}"
          :before-upload="beforeAvatarUpload"
          action="#"
          :http-request="function(file, fileList) {return handleChange(file, fileList, 'otherFileList') }">
          <el-button type="primary" size="mini">选择上传</el-button>
          <div slot="tip" class="cumost-upload-tip">
            支持图片和pdf
          </div>
        </el-upload>
         </div>
         </el-card>
  </div>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button size="small" @click="visible = false"
        >取 消</el-button
      >
      <el-button size="small" :loading="loading" type="primary" @click="submitAddly('storeForm')"
        >提交</el-button
      >
    </div>

    <el-dialog title="图片预览" append-to-body :visible.sync="innerVisible">
      <img :src="previewUrl" alt="图片预览" class="previcew-img" />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="innerVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog
      :title="tips.title"
      append-to-body
      width="600px"
      :visible.sync="tips.visible"
    >
      <div v-if="tips.type == 1" class="shili-box">
        <div v-if="ruleForm.egimg1">
          <label>{{ ruleForm.egimg1 }}</label>
        </div>
        <img :src="item.url" v-for="item in egimg1FileList" :key="item.url"/>
        <el-empty v-if="!ruleForm.egimg1 && egimg1FileList.length == 0" description="暂无示例信息"></el-empty>
      </div>
      <div v-if="tips.type == 2" class="shili-box">
        <div v-if="ruleForm.egimg2">
          <label>{{ ruleForm.egimg2 }}</label>
        </div>
        <img :src="item.url" v-for="item in egimg2FileList" :key="item.url"/>
        <el-empty v-if="!ruleForm.egimg2 && egimg2FileList.length == 0" description="暂无示例信息"></el-empty>
      </div>
      <div v-if="tips.type == 3" class="shili-box">
        <div v-if="ruleForm.egimg3">
          <label>{{ ruleForm.egimg3 }}</label>
        </div>
        <img :src="item.url" v-for="item in egimg3FileList" :key="item.url"/>
        <el-empty v-if="!ruleForm.egimg3 && egimg3FileList.length == 0" description="暂无示例信息"></el-empty>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="tips.visible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </el-dialog>
</template>

<script>
import moment from "moment";
import { mapGetters, mapActions } from "vuex";
import { getSupplierCategoryTree,supplierStoreApply } from "@/api/supplier_api";
import { getDetailByKey } from "@/api/about_api";
import pdfimg from "@/assets/pdf_file.png";
import {TreeArrar} from '@/utils/index'
export default {
  props: {
    title: {
      type: String,
      default: () => {
        return "";
      }
    }
  },
  data() {
    return {
      visible: false,
      innerVisible: false,
      previewUrl: "",
      treeData: [],
      storeForm: {
        supplierStoreIds: [],
        isType: 1,
        qualificationCertificateFileReason: "",
        otherRemarks:""
      },
      qualificationCertificateFileList: [],
      performanceFileList: [],
      financialReportFileList: [],
      taxFileList: [],
      socialSecurityFileList: [],
      businessCreditFileList: [],
      otherFileList: [],
      //示例
      tips: {
        visible: false,
        type: 1,
        title: ""
      },
      ruleForm: {
        egimg1: "",
        egimg2: "",
        egimg3: ""
      },
      loading:false,
      egimg1FileList: [],
      egimg2FileList: [],
      egimg3FileList: []
    };
  },
  mounted() {},
  methods: {
    ...mapActions({
      uploadFile: "user/uploadFile"
    }),
    openStoreForm() {
      this.categoryList()
    },
    async categoryList() {
        const { code, data } = await getSupplierCategoryTree();
      if (code == 200) {
       if (data && data.length) {
          let NewData = data.map((ele) => TreeArrar(ele))
         this.treeData = NewData
           this.visible = true;
       } else {
          this.$confirm('入驻类型未配置数据，请联系管理员配置，否则无法申请入库?', '温馨提示', {
            confirmButtonText: '关闭',
            showCancelButton:false,
            type: 'warning'
          }).then(() => { }).catch(() => {});
       }
     }
    },
    async getKeyResult(dataKey,dataTitle) {
      this.egimg1FileList = [];
        this.egimg2FileList = [];
        this.egimg3FileList = [];
        let { code, data } = await getDetailByKey(dataKey);
      if (code === 200) {
        this.tips.visible = true
          this.tips.title = dataTitle
          const regex = /#~#/;
        if (data && "egimg1" == data.key) {
            this.tips.type = 1
            if (data.value) {
              if (regex.test(data.value)) {
                const parts = data.value.split("#~#");
                this.ruleForm.egimg1 = parts[0];
                this.egimg1FileList = JSON.parse(parts[1]);
              } else {
                this.egimg1FileList = JSON.parse(data.value);
              }
            }
          }
          if (data && "egimg2" == data.key) {
            this.tips.type = 2
            if (data.value) {
              if (regex.test(data.value)) {
                const parts = data.value.split("#~#");
                this.ruleForm.egimg2 = parts[0];
                this.egimg2FileList = JSON.parse(parts[1]);
              } else {
                this.egimg2FileList = JSON.parse(data.value);
              }
            }
          }
          if (data && "egimg3" == data.key) {
            this.tips.type = 3
            if (data.value) {
              if (regex.test(data.value)) {
                const parts = data.value.split("#~#");
                this.ruleForm.egimg3 = parts[0];
                this.egimg3FileList = JSON.parse(parts[1]);
              } else {
                this.egimg3FileList = JSON.parse(data.value);
              }
            }
          }
        }
    },
    handlePreview(file) {
      if (file.type == 1) {
        window.open(file.urls);
      } else {
        this.previewUrl = file.url;
        this.innerVisible = true;
      }
    },
    handleRemove(file, fileList, fliedKey) {
      const index = this[fliedKey].indexOf(file);
      if (index > -1) {
        this[fliedKey].splice(index, 1);
      }
    },
    async handleChange(file, fileList, fileKey) {
      const url = await this.uploadFile({ fileKey: fileKey, data: file });
      if (url) {
        if (file.file.type == "application/pdf") {
          this[fileKey].push({
            name: file.file.name,
            time:[],
            url: pdfimg,
            urls: url,
            type: 1
          });
        } else {
          this[fileKey].push({ name: file.file.name, url: url, type: 2,time:[] });
        }
      }
    },
    beforeAvatarUpload(file) {
      const isJPG =
        file.type === "image/jpeg" ||
        file.type === "image/png" ||
        file.type === "image/jpg" ||
        file.type === "application/pdf";

      const isLt200M = file.size / 1024 / 1024 < 200;

      if (!isJPG) {
        this.$message.error("附件只能是 jpeg，png，jpg 格式或pdf格式!");
      }

      if (!isLt200M) {
        this.$message.error("附件大小不能超过 200MB!");
      }

      return isJPG && isLt200M;
    },
      // 根据 value 查找完整的中文路径
    findLabelPathByValue(options, value, path = []) {
      for (const item of options) {
        // 当前路径
        const currentPath = [...path, item.label];

        // 如果找到匹配的 value
        if (item.value === value) {
          let param = {}
          param.id = item.value
          param.name = currentPath.join('/');
          return param
         // return currentPath.join('/');
        }

        // 如果有子节点，递归查找
        if (item.children) {
          const result = this.findLabelPathByValue(item.children, value, currentPath);
          if (result) return result;
        }
      }
      return null;
    },
    submitAddly(formName) {
      let that = this
      this.$refs[formName].validate(async valid => { 
        if (valid) { 
          let param = {}
          param.isUploadQualificationCertificateFile = this.storeForm.isType
          if (this.storeForm.isType == 1) {
            if (this.qualificationCertificateFileList.length == 0) {
              this.$message.error('请上传资质证书');
              return;
            }

            for (let i = 0; i < this.qualificationCertificateFileList.length; i++){
              let vals = this.qualificationCertificateFileList[i]
              if (vals.time.length == 0) {
                let txt = '资质证书（附件名称）' + vals.name + '未填写开始结束日期！'
                this.$message.error(txt);
                return;
              }
            }

            param.qualificationCertificateFile = JSON.stringify(this.qualificationCertificateFileList)
          } else {
            if (!this.storeForm.qualificationCertificateFileReason) {
              this.$message.error('请填写不上传资质证书理由');
              return;
            }
            param.qualificationCertificateFileReason = this.storeForm.qualificationCertificateFileReason
          }
          if (this.performanceFileList.length == 0) {
              this.$message.error('请上传业绩资料');
              return;
          }
          param.performanceFile = JSON.stringify(this.performanceFileList)
             if (this.financialReportFileList.length == 0) {
              this.$message.error('请上传财务报告');
              return;
             }
             param.financialReportFile = JSON.stringify(this.financialReportFileList)
             if (this.taxFileList.length == 0) {
              this.$message.error('请上传缴纳税收证明或完税证明');
              return;
             }
            param.taxProofFile = JSON.stringify(this.taxFileList)
             if (this.socialSecurityFileList.length == 0) {
              this.$message.error('请上传缴纳社保证明');
              return;
             }
             param.socialSecurityFile = JSON.stringify(this.socialSecurityFileList)
            if (this.businessCreditFileList.length == 0) {
              this.$message.error('请上传商业信誉');
              return;
            }
          param.businessCreditFile = JSON.stringify(this.businessCreditFileList)
            
          if (this.otherFileList.length >= 1) {
              param.otherFile = JSON.stringify(this.otherFileList)
          }

          if (this.storeForm.otherRemarks) {
            param.otherRemarks = this.storeForm.otherRemarks
          }
          
          param.storeType = '1'
            
          const selectedLabels = this.storeForm.supplierStoreIds.map(value =>
            this.findLabelPathByValue(this.treeData, value)
          );
          param.supplierStoreList = selectedLabels

          let supplierStoreName = selectedLabels.map(v=>v.name)
         
          param.supplierStoreName = JSON.stringify(supplierStoreName)
          this.loading = true
          try {
            const { code } = await supplierStoreApply(param)
            if (code == 200) {
              this.$alert('申请入库成功，审核结果通过短信发送到手机！', '温馨提示', {
                confirmButtonText: '关闭',
                type:'success',
                callback: action => {
                  that.clearData()
                }
              }).catch(() => {
                that.clearData()    
              });
            }
          } finally {
              this.loading = false
          }
        }
      })
    },
    typeChange(e) {
      if (e == 1) {
        this.storeForm.qualificationCertificateFileReason = ''
      } else {
        this.qualificationCertificateFileList = []
      }
    },
    clearData() {
      this.storeForm = {
        supplierStoreIds: [],
        isType: 1,
        qualificationCertificateFileReason: "",
        otherRemarks: ""
      },
      this.qualificationCertificateFileList = []
      this.performanceFileList = []
      this.financialReportFileList = []
      this.taxFileList = []
      this.socialSecurityFileList = []
      this.businessCreditFileList = []
      this.otherFileList = []
      this.$emit('success')
    }
  }
};
</script>
<style scoped>
.cumost-upload-tip {
  font-size: 12px;
  color: #606266;
  display: inline-block;
  margin-left: 20px;
}
.shili-box label{
  text-align: center;
  padding: 10px;
  font-size: 20px;
  display: block;
  color: #000;
}
.shili-box img{
  display: block;
  margin: 10px auto;
  max-width: 100%;
}
.mut-box{
  min-height: 140px;
}
.cumot-filex{
  display: flex;
  grid-column-gap: 2%;
  flex-wrap: wrap;
}
.box-card{
  flex: 0 0 49%;
}
.box-card span:before {
    content: '*';
    color: #F56C6C;
    margin-right: 4px;
}
.blocks-file{
  display: flex;
  flex-direction: column;
  margin-top: 15px;
}
.demonstration{
  word-break: break-word;
  margin-bottom: 4px;
}
.lbs{
  flex: 1;
}

</style>


<!--

<template>
  <el-dialog
    :title="title"
    :visible.sync="visible"
    width="1000px"
    :close-on-click-modal="false"
  >
   <el-form
      size="small"
      :model="storeForm"
      ref="storeForm"
      label-position="top">
   <el-row :gutter="20">
    <el-col :span="12">
        <el-form-item
        label="入驻类型"
        prop="supplierStoreIds"
        :rules="[
          { required: true, message: '请选择入驻类型', trigger: 'change' }
        ]"
      >
        <el-cascader
          style="width:100%"
          placeholder="请选择入驻类型，支持搜索"
          filterable
          v-model="storeForm.supplierStoreIds"
          :options="treeData"
          :props="{multiple: true}"
          clearable
        ></el-cascader>
      </el-form-item>
    </el-col>
    <el-col :span="12">
        <el-form-item label="是否上传资质证书">
        <el-radio-group v-model="storeForm.isType">
          <el-radio :label="1">是</el-radio>
          <el-radio :label="2">否</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-col>
    </el-row>
       

  <el-row :gutter="20">
    <el-col :span="12">
       <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>上传资质证书</span>
          <el-button style="float: right;padding:0;" type="text">选择上传</el-button>
        </div>
        <el-form-item
          prop="qualificationCertificateFileList"
          :rules="[
            { required: true, message: '请上传资质证书', trigger: 'change' }
          ]"
        >
          <el-upload
            accept="image/*,application/pdf"
            list-type="picture"
            v-model="storeForm.qualificationCertificateFileList"
            :on-preview="handlePreview"
            :file-list="qualificationCertificateFileList"
            :on-remove="function(file, fileList) {return handleRemove(file, fileList, 'qualificationCertificateFileList')}"
            :before-upload="beforeAvatarUpload"
            action="#"
            :http-request="function(file, fileList) { return handleChange( file, fileList, 'qualificationCertificateFileList')}">
            <el-button type="primary" size="mini">上传</el-button>
            <div slot="tip" class="cumost-upload-tip">
              支持图片和pdf
            </div>
          </el-upload>
        </el-form-item>
      </el-card>
    </el-col>
    <el-col :span="12">
     <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>不上传资质理由</span>
          <el-button style="float: right;padding:0;"  type="text">选择上传</el-button>
        </div>

      </el-card>
    </el-col>
  </el-row>
   
     
      <template v-if="storeForm.isType == 2">
        <el-form-item
          label="不上传资质理由"
          prop="qualificationCertificateFileList"
          :rules="[
            { required: true, message: '请输入不上传资质理由', trigger: 'blur' }
          ]"
        >
          <el-input
            type="textarea"
            :rows="3"
            v-model="storeForm.qualificationCertificateFileList"
            placeholder="请输入不上传资质理由"
          ></el-input>
        </el-form-item>
      </template>
      <template v-if="storeForm.isType == 1">
        <el-form-item
          label="上传资质证书"
          prop="qualificationCertificateFileList"
          :rules="[
            { required: true, message: '请上传资质证书', trigger: 'change' }
          ]"
        >
          <el-upload
            accept="image/*,application/pdf"
            list-type="picture"
            v-model="storeForm.qualificationCertificateFileList"
            :on-preview="handlePreview"
            :file-list="qualificationCertificateFileList"
            :on-remove="function(file, fileList) {return handleRemove(file, fileList, 'qualificationCertificateFileList')}"
            :before-upload="beforeAvatarUpload"
            action="#"
            :http-request="function(file, fileList) { return handleChange( file, fileList, 'qualificationCertificateFileList')}">
            <el-button type="primary" size="mini">上传</el-button>
            <div slot="tip" class="cumost-upload-tip">
              支持图片和pdf
            </div>
          </el-upload>
        </el-form-item>
      </template>

      <el-form-item
        label="上传业绩资料"
        prop="performanceFileList"
        :rules="[
          { required: true, message: '请上传业绩资料', trigger: 'change' }
        ]"
      >
        <el-upload
          v-model="storeForm.performanceFileList"
          accept="image/*,application/pdf"
          list-type="picture"
          :on-preview="handlePreview"
          :file-list="performanceFileList"
          :on-remove="function(file, fileList) {return handleRemove(file, fileList, 'performanceFileList')}"
          :before-upload="beforeAvatarUpload"
          action="#"
          :http-request="function(file, fileList) {return handleChange(file, fileList, 'performanceFileList')}">
          <el-button type="primary" size="mini">上传</el-button>
          <div slot="tip" class="cumost-upload-tip">
            支持图片和pdf
          </div>
        </el-upload>
      </el-form-item>
      <el-form-item
        label="上传财务报告（报表）"
        prop="financialReportFileList"
        :rules="[
          {
            required: true,
            message: '请上传财务报告（报表）',
            trigger: 'change'
          }
        ]"
      >
        <el-upload
          v-model="storeForm.financialReportFileList"
          accept="image/*,application/pdf"
          list-type="picture"
          :on-preview="handlePreview"
          :file-list="financialReportFileList"
          :on-remove="function(file, fileList) { return handleRemove(file, fileList, 'financialReportFileList') }"
          :before-upload="beforeAvatarUpload"
          action="#"
          :http-request="function(file, fileList) { return handleChange(file, fileList, 'financialReportFileList') }">
          <el-button type="primary" size="mini">上传</el-button>
          <div slot="tip" class="cumost-upload-tip">
            支持图片和pdf
          </div>
        </el-upload>
      </el-form-item>
      <el-form-item
        label="缴纳税收证明或完税证明"
        prop="taxFileList"
        :rules="[
          {
            required: true,
            message: '请上传缴纳税收证明或完税证明',
            trigger: 'change'
          }
        ]"
      >
        <el-upload
          v-model="storeForm.taxFileList"
          accept="image/*,application/pdf"
          list-type="picture"
          :on-preview="handlePreview"
          :file-list="taxFileList"
          :on-remove="function(file, fileList) { return handleRemove(file, fileList, 'taxFileList') }"
          :before-upload="beforeAvatarUpload"
          action="#"
          :http-request="function(file, fileList) {return handleChange(file, fileList, 'taxFileList')}">
          <el-button type="primary" size="mini">上传</el-button>
          <div slot="tip" class="cumost-upload-tip">
            支持图片和pdf
            <el-button type="text" @click="getKeyResult('egimg1','缴纳税收证明或完税证明示例图')" size="mini">【查看示例图】</el-button>
          </div>
        </el-upload>
      </el-form-item>
      <el-form-item
        label="缴纳社保证明"
        prop="socialSecurityFileList"
        :rules="[
          { required: true, message: '请上传缴纳社保证明', trigger: 'change' }
        ]"
      >
        <el-upload
          v-model="storeForm.socialSecurityFileList"
          accept="image/*,application/pdf"
          list-type="picture"
          :on-preview="handlePreview"
          :file-list="socialSecurityFileList"
          :on-remove="function(file, fileList) { return handleRemove(file, fileList, 'socialSecurityFileList')}"
          :before-upload="beforeAvatarUpload"
          action="#"
          :http-request="function(file, fileList) { return handleChange(file, fileList, 'socialSecurityFileList')}">
          <el-button type="primary" size="mini">上传</el-button>
          <div slot="tip" class="cumost-upload-tip">
            支持图片和pdf
            <el-button type="text" @click="getKeyResult('egimg2','缴纳社保证明示例图')" size="mini">【查看示例图】</el-button>
          </div>
        </el-upload>
      </el-form-item>
      <el-form-item
        label="良好的商业信誉"
        prop="businessCreditFileList"
        :rules="[
          { required: true, message: '请上传良好的商业信誉', trigger: 'blur' }
        ]"
      >
        <el-upload
          v-model="storeForm.businessCreditFileList"
          accept="image/*,application/pdf"
          list-type="picture"
          :on-preview="handlePreview"
          :file-list="businessCreditFileList"
          :on-remove="function(file, fileList) {return handleRemove(file, fileList, 'businessCreditFileList')}"
          :before-upload="beforeAvatarUpload"
          action="#"
          :http-request="function(file, fileList) {return handleChange(file, fileList, 'businessCreditFileList')}">
          <el-button type="primary" size="mini">上传</el-button>
          <div slot="tip" class="cumost-upload-tip">
            支持图片和pdf
            <el-button type="text" @click="getKeyResult('egimg3','商业信誉示例图')" size="mini">【查看示例图】</el-button>
          </div>
        </el-upload>
      </el-form-item>
      <el-form-item
        label="其他"
        prop="otherFileList"
        :rules="[
          { required: true, message: '请上传其他附件', trigger: 'change' }
        ]"
      >
        <el-upload
          v-model="storeForm.otherFileList"
          accept="image/*,application/pdf"
          list-type="picture"
          :on-preview="handlePreview"
          :file-list="otherFileList"
          :on-remove="function(file, fileList) {return handleRemove(file, fileList, 'otherFileList')}"
          :before-upload="beforeAvatarUpload"
          action="#"
          :http-request="function(file, fileList) {return handleChange(file, fileList, 'otherFileList') }">
          <el-button type="primary" size="mini">上传</el-button>
          <div slot="tip" class="cumost-upload-tip">
            支持图片和pdf
          </div>
        </el-upload>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button size="small" @click="storeForm.visible = false"
        >取 消</el-button
      >
      <el-button size="small" type="primary" @click="submitAddly('storeForm')"
        >提交</el-button
      >
    </div>

    <el-dialog title="图片预览" append-to-body :visible.sync="innerVisible">
      <img :src="previewUrl" alt="图片预览" class="previcew-img" />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="innerVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog
      :title="tips.title"
      append-to-body
      width="600px"
      :visible.sync="tips.visible"
    >
      <div v-if="tips.type == 1" class="shili-box">
        <div v-if="ruleForm.egimg1">
          <label>{{ ruleForm.egimg1 }}</label>
        </div>
        <img :src="item.url" v-for="item in egimg1FileList" :key="item.url"/>
        <el-empty v-if="!ruleForm.egimg1 && egimg1FileList.length == 0" description="暂无示例信息"></el-empty>
      </div>
      <div v-if="tips.type == 2" class="shili-box">
        <div v-if="ruleForm.egimg2">
          <label>{{ ruleForm.egimg2 }}</label>
        </div>
        <img :src="item.url" v-for="item in egimg2FileList" :key="item.url"/>
        <el-empty v-if="!ruleForm.egimg2 && egimg2FileList.length == 0" description="暂无示例信息"></el-empty>
      </div>
      <div v-if="tips.type == 3" class="shili-box">
        <div v-if="ruleForm.egimg3">
          <label>{{ ruleForm.egimg3 }}</label>
        </div>
        <img :src="item.url" v-for="item in egimg3FileList" :key="item.url"/>
        <el-empty v-if="!ruleForm.egimg3 && egimg3FileList.length == 0" description="暂无示例信息"></el-empty>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="tips.visible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </el-dialog>
</template>

<script>
import moment from "moment";
import { mapGetters, mapActions } from "vuex";
import { getSupplierCategoryTree } from "@/api/supplier_api";
import { getDetailByKey } from "@/api/about_api";
import pdfimg from "@/assets/pdf_file.png";
export default {
  props: {
    title: {
      type: String,
      default: () => {
        return "";
      }
    }
  },
  data() {
    return {
      visible: false,
      innerVisible: false,
      previewUrl: "",
      treeData: [],
      storeForm: {
        supplierStoreIds: [],
        isType: 1,
        qualificationCertificateFileList: "",
        performanceFileList: "",
        financialReportFileList: "",
        taxFileList: "",
        socialSecurityFileList: "",
        businessCreditFileList: "",
        otherFileList: ""
      },
      qualificationCertificateFileList: [],
      performanceFileList: [],
      financialReportFileList: [],
      taxFileList: [],
      socialSecurityFileList: [],
      businessCreditFileList: [],
      otherFileList: [],
      //示例
      tips: {
        visible: false,
        type: 1,
        title: ""
      },
      ruleForm: {
        egimg1: "",
        egimg2: "",
        egimg3: ""
      },
      egimg1FileList: [],
      egimg2FileList: [],
      egimg3FileList: []
    };
  },
  mounted() {},
  methods: {
    ...mapActions({
      uploadFile: "user/uploadFile"
    }),
    openStoreForm() {
      this.categoryList()
    },
    async categoryList() {
        const { code, data } = await getSupplierCategoryTree();
      if (code == 200) {
       if (data && data.length) {
          let NewData = data.map((ele) => this.TreeArrar(ele))
         this.treeData = NewData
           this.visible = true;
       } else {
          this.$confirm('入驻类型未配置数据，请联系管理员配置?', '温馨提示', {
            confirmButtonText: '关闭',
            showCancelButton:false,
            type: 'warning'
          }).then(() => { }).catch(() => {});
       }
     }
    },
    TreeArrar(data){
        const hasChild = data.children && data.children.length > 0
        return {
            label: data.categoryName,
            value: data.id,
            children: hasChild ? data.children.map((i) => this.TreeArrar(i)) : null
        }
    },
    async getKeyResult(dataKey,dataTitle) {
      this.egimg1FileList = [];
        this.egimg2FileList = [];
        this.egimg3FileList = [];
        let { code, data } = await getDetailByKey(dataKey);
      if (code === 200) {
        this.tips.visible = true
          this.tips.title = dataTitle
          const regex = /#~#/;
        if (data && "egimg1" == data.key) {
            this.tips.type = 1
            if (data.value) {
              if (regex.test(data.value)) {
                const parts = data.value.split("#~#");
                this.ruleForm.egimg1 = parts[0];
                this.egimg1FileList = JSON.parse(parts[1]);
              } else {
                this.egimg1FileList = JSON.parse(data.value);
              }
            }
          }
          if (data && "egimg2" == data.key) {
            this.tips.type = 2
            if (data.value) {
              if (regex.test(data.value)) {
                const parts = data.value.split("#~#");
                this.ruleForm.egimg2 = parts[0];
                this.egimg2FileList = JSON.parse(parts[1]);
              } else {
                this.egimg2FileList = JSON.parse(data.value);
              }
            }
          }
          if (data && "egimg3" == data.key) {
            this.tips.type = 3
            if (data.value) {
              if (regex.test(data.value)) {
                const parts = data.value.split("#~#");
                this.ruleForm.egimg3 = parts[0];
                this.egimg3FileList = JSON.parse(parts[1]);
              } else {
                this.egimg3FileList = JSON.parse(data.value);
              }
            }
          }
        }
    },
    handlePreview(file) {
      if (file.type == 1) {
        window.open(file.urls);
      } else {
        this.previewUrl = file.url;
        this.innerVisible = true;
      }
    },
    handleRemove(file, fileList, fliedKey) {
      const index = this[fliedKey].indexOf(file);
      if (index > -1) {
        this[fliedKey].splice(index, 1);
        if (this[fliedKey].length == 0) {
          this.storeForm[fliedKey] = ''
        }
      }
    },
    async handleChange(file, fileList, fileKey) {
      const url = await this.uploadFile({ fileKey: fileKey, data: file });
      if (url) {
        if (file.file.type == "application/pdf") {
          this[fileKey].push({
            name: file.file.name,
            url: pdfimg,
            urls: url,
            type: 1
          });
        } else {
          this[fileKey].push({ name: file.file.name, url: url, type: 2 });
        }
        this.storeForm[fileKey] = url
      }
    },
    beforeAvatarUpload(file) {
      const isJPG =
        file.type === "image/jpeg" ||
        file.type === "image/png" ||
        file.type === "image/jpg" ||
        file.type === "application/pdf";
      if (!isJPG) {
        this.$message.error("附件只能是 jpeg，png，jpg 格式或pdf格式!");
      }
      return isJPG;
    },
    submitAddly(formName) {
      this.$refs[formName].validate(async valid => { 
        if (valid) { 
          console.log(this.storeForm)
        }
      })
    }
  }
};
</script>
<style scoped>
.cumost-upload-tip {
  font-size: 12px;
  color: #606266;
  display: inline-block;
  margin-left: 20px;
}
.shili-box label{
  text-align: center;
  padding: 10px;
  font-size: 20px;
  display: block;
  color: #000;
}
.shili-box img{
  display: block;
  margin: 10px auto;
  max-width: 100%;
}

</style>


-->